﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.ComponentModel;

namespace WebComponents.Data
{
    public class GetData
    {
        public static DataTable DataTable(string StoredProcedure, List<ISqlParameter> SqlParameter)
        {
            DataTable dt = new DataTable();
            string connectionString = SiteConfiguration.ConnectionString;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(StoredProcedure))
                {
                    cmd.CommandType = CommandType.Text;
                    if (SqlParameter != null)
                    {
                        foreach (ISqlParameter item in SqlParameter)
                        {
                            cmd.Parameters.Add(new SqlParameter(item.name, item.value));
                        }
                    }
                    conn.Open();
                    cmd.Connection = conn;
                    SqlDataAdapter daAdapter = null;
                    daAdapter = new SqlDataAdapter(cmd);
                    daAdapter.Fill(dt);
                }
            } 
            return dt;
        }

        public static void Run(string StoredProcedure, List<ISqlParameter> SqlParameter)
        {
            string connectionString = SiteConfiguration.ConnectionString;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(StoredProcedure))
                {
                    cmd.CommandType = CommandType.Text;
                    if (SqlParameter != null)
                    {
                        foreach (ISqlParameter item in SqlParameter)
                        {
                            cmd.Parameters.Add(new SqlParameter(item.name, item.value));
                        }
                    }
                    conn.Open();
                    cmd.Connection = conn;
                    cmd.ExecuteNonQuery();
                }
            }
        }

        private static DataTable dtError(string errorMessage)
        {
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn();
            dc.DataType = System.Type.GetType("System.String");
            dc.ColumnName = "Error";
            dt.Columns.Add(dc);

            DataRow dr = dt.NewRow();
            dr["Error"] = errorMessage.ToString();
            dt.Rows.Add(dr);

            return dt;
        }
 
        public class ISqlParameter
        {
            public string name { get; set; }
            public string value { get; set; }
        }
    }
}
